<?php

namespace App\Service\Cruise\Mission;

use App\Library\Rms\RmsShopApi;
use App\Library\Rms\RmsUserApi;
use App\Models\BaseModel;
use App\Models\Common\ConfigModel;
use App\Models\Common\FsCompanyModel;
use App\Models\Common\FsCompanyRoleMappingModel;
use App\Models\Common\FsCompanyUserMappingModel;
use App\Models\Cruise\CruiseCheckCompanyModel;
use App\Models\Cruise\CruiseCheckDetailModel;
use App\Models\Cruise\CruiseCheckErrorModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseOrderProcessModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopAddressModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\Shop\ShopModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\BaseService;
use App\Service\Cruise\Check\CruiseCheckAgainstService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\OpenShop\Feishu\OrganizationManageUserService;
use App\Service\OpenShop\User\RmsUserService;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;

class CruiseMissionService
{
    /**
     *
     * 代办列表
     * @param $status
     * @param $pageNum
     * @param $pageSize
     * @param $name
     * @param $shopCode
     * @param $cityCode
     * @param $orderPermission
     * @param $type 1 新店帮扶  3 稽核
     * @param string $taskName
     * @param string $shopIds
     * @param string $startDate
     * @param string $endDate
     * @param int $inspector
     * @param int $handle
     * @return array
     * @throws GuzzleException
     */
    public static function getMissionList($status, $pageNum, $pageSize, $name, $shopCode, $cityCode, $orderPermission, $type, $companyName, string $taskName = '', string $shopIds = '', string $startDate = '', string $endDate = '', int $inspector = 0, int $handle = 0, array $cruiseCheckCompanyIds = [], string $platformName = ''): array
    {
        $shopIds = $shopIds ? explode(',', $shopIds) : [];

        $paginator    = CruiseOrderModel::query()
            ->orderByDesc('updatedAt')
            ->where('type', $type)
            ->when(mb_strlen($startDate) && mb_strlen($endDate), function ($query) use ($startDate, $endDate) {
                $query->whereBetween('createdAt', [strtotime($startDate), strtotime($endDate) + 86400]);
            })
            ->when($shopIds, function ($query) use ($shopIds) {
                $query->whereIn('shopId', $shopIds);
            })
            ->when(mb_strlen($name), function ($query) use ($name) {
                $query->whereRaw("orderNo in (select `orderNo` from `open_shop_main_process` where orderNo in (select `orderNo` from `open_shop_user_identity_card` where `name` like '%{$name}%') order by `open_shop_main_process`.`id` desc)");
            })
            ->when(mb_strlen($taskName), function ($query) use ($taskName) {
                $query->whereRaw("id in (select `orderId` from `cruise_task_order_mappings` where taskId in (select `id` from `cruise_check_tasks` where `name` like '%{$taskName}%') order by `cruise_task_order_mappings`.`id` desc)");
            })
            ->when(mb_strlen($companyName), function ($query) use ($companyName) {
                $query->whereRaw("cruiseCheckCompanyId in (select `id` from `cruise_check_company` where fsCompanyId in (select `id` from `fs_company` where `name` like '%{$companyName}%'))");
            })
            ->when($inspector, function ($query) use ($inspector) {
                $query->whereRaw("id in (select `orderId` from `cruise_check_details` where `dealUid` = $inspector)");
            })
            ->when($handle, function ($query) use ($handle) {
                $query->where('handlerId', $handle);
            })
            ->when(mb_strlen($platformName) && $type == CruiseOrderModel::TYPE_COMPANY_CHECK, function ($query) use ($platformName) {
                switch ($platformName) {
                    case 'cruiseCheck':
                        $checkType = CruiseCheckDetailModel::CHECK_TYPE_INSIDE;
                        break;
                    case 'cruiseCheckSupplier':
                        $checkType = CruiseCheckDetailModel::CHECK_TYPE_THIRD_PARTY;
                        break;
                    default:
                        return;
                }
                $query->whereRaw("id in (select `orderId` from `cruise_check_details` where `checkType` = $checkType)");
            })
            ->when(mb_strlen($shopCode), function ($query) use ($shopCode) {
                $child = OpenShopSignOrderModel::query()
                    ->where('shopCode', $shopCode)
                    ->select('orderNo');
                $query->whereRaw("orderNo in (" . BaseModel::toSqlWithParam($child) . ')');
            })
            ->when($cityCode, function ($query) use ($cityCode) {
                $child = OpenShopAddressModel::query()
                    ->where('cityCode', $cityCode)
                    ->select('orderNo');
                $query->whereRaw("orderNo in (" . BaseModel::toSqlWithParam($child) . ')');
            })
            ->when($status, function ($query) use ($status) {
                if ($status == CruiseOrderModel::STATUS_NOT_REVIEW) {
                    $query->whereIn('status', [CruiseOrderModel::STATUS_NOT_REVIEW, CruiseOrderModel::STATUS_WAIT_MODIFY_EXT]);
                } else {
                    $query->where('status', $status);
                }
            })
            ->when(!$orderPermission['isAll'], function ($query) use ($orderPermission) {
                $query->whereRaw($orderPermission['rawSql']);
            })
            ->when($cruiseCheckCompanyIds, function ($query) use ($cruiseCheckCompanyIds) {
                $query->whereIn('cruiseCheckCompanyId', $cruiseCheckCompanyIds);
            })
            ->with(['userIdentityCardRel', 'siteLocationRel', 'cruiseCheckTaskRel', 'checkTaskDetailRel', 'cruiseTemplateRel', 'cruiseCheckSelfDetailRel'])
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
        $checkUserIds = [];
        $paginator->each(function (CruiseOrderModel $cruiseOrder) use (&$checkUserIds) {
            $checkUserIds[] = (int)optional($cruiseOrder->checkTaskDetailRel)->dealUid;
        });

            //获取处理人
        $userInfo = RmsUserService::getRmsUserInfoByUserIds(array_merge($paginator->pluck('handlerId')->toArray(), $checkUserIds))['data'] ?? [];

        if ($type != CruiseTemplateModel::TYPE_5) {
            $shopInfo = (new RmsShopApi())->getShopByIds($paginator->pluck('shopId')->toArray(), ['id', 'shopCode', 'name'])['data']['shopList'] ?? [];
        } else {
            $shopInfo = [];
        }

        $userList = array_column($userInfo, 'username', 'id');
        $shopList = array_column($shopInfo, null, 'id');
        $list     = $paginator->map(function (CruiseOrderModel $cruiseOrder) use ($type, $userList, $shopList) {
            //项目类型
            $sysTemplate = (int)optional($cruiseOrder->checkTaskDetailRel)->sysTemplate;
            if ($cruiseOrder->userIdentityCardRel->count()) {
                $name = $cruiseOrder->userIdentityCardRel[0]->name;
            } else {
                $name = '-';
            }

            // 机构信息
            if ($cruiseOrder->cruiseCheckCompanyId) {
                $cruiseCheckCompany = CruiseCheckCompanyModel::getDataById($cruiseOrder->cruiseCheckCompanyId);
            } else {
                $cruiseCheckCompany = [];
            }

            return [
                'id'          => $cruiseOrder->id,
                'orderNo'     => $cruiseOrder->orderNo,
                'shopId'      => $cruiseOrder->shopId,
                'missionType' => $type == CruiseOrderModel::TYPE_NEW_SHOP_HELP ? '新店帮扶' : '',
                'userName'    => $name,
                'shopInfo'    => $type == CruiseOrderModel::TYPE_COMPANY_CHECK ? '' : ('KF' . sprintf("%04d", ($shopList[$cruiseOrder->shopId]['shopCode'] ?? '0000')) . ' ' . ($shopList[$cruiseOrder->shopId]['name'] ?? '-')),
                'shopCode'    => $shopList[$cruiseOrder->shopId]['shopCode'] ?? '-',
                'shopName'    => $shopList[$cruiseOrder->shopId]['name'] ?? '-',
                'shopArea'    => (string)optional($cruiseOrder->siteLocationRel)->cityArea ?: '-',
                'updateTime'  => $cruiseOrder->updatedAt->toDateTimeString(),
                'createTime'  => $cruiseOrder->createdAt->toDateTimeString(),
                'status'      => $cruiseOrder->status,
                'taskName'    => $cruiseOrder->getTaskName(),
                'sysTemplate' => $sysTemplate,
                'taskType'    => CruiseTemplateModel::SYS_TEMPLATE_TEXT[$sysTemplate] ?? '-',
                'statusText'  => CruiseOrderModel::CRUISE_STATUS_MAPPING[$cruiseOrder->status] ?? '未知任务状态',
                'handler'     => $userList[$cruiseOrder->handlerId] ?? '-',
                'checkUser'   => $userList[(int)optional($cruiseOrder->checkTaskDetailRel)->dealUid] ?? '-',
                'checkId'     => (int)optional($cruiseOrder->checkTaskDetailRel)->id,
                'companyName'    => $cruiseCheckCompany['fsCompany']['name'] ?? '',
                'companyContact'   => $cruiseCheckCompany['companyManager']['phone'] ?? '',
            ];
        });
        return [
            'list'      => $list,
            'count'     => $paginator->total(),
            'pageCount' => $paginator->lastPage(),
            'pageNum'   => $pageNum,
            'pageSize'  => $pageSize,
        ];
    }

    /**
     * 获得代办状态的数字统计
     * @param $orderPermission
     * @param $type
     * @param $level
     * @param $cityCode
     * @return int[]
     */
    public static function getMissionCount($orderPermission, $type, $level, $cityCode, $platformName = ''): array
    {
        $notSubmit = 0;
        $notReview = 0;
        $notModify = 0;
        $completed = 0;
        $collected = 0;
        $closed    = 0;
        CruiseOrderModel::query()
            ->where('type', $type)
            ->when(!$orderPermission['isAll'], function ($query) use ($orderPermission) {
                $query->whereRaw($orderPermission['rawSql']);
            })
            ->when(mb_strlen($platformName) && $type == CruiseOrderModel::TYPE_COMPANY_CHECK, function ($query) use ($platformName) {
                switch ($platformName) {
                    case 'cruiseCheck':
                        $checkType = CruiseCheckDetailModel::CHECK_TYPE_INSIDE;
                        break;
                    case 'cruiseCheckSupplier':
                        $checkType = CruiseCheckDetailModel::CHECK_TYPE_THIRD_PARTY;
                        break;
                    default:
                        return;
                }
                $query->whereRaw("id in (select `orderId` from `cruise_check_details` where `checkType` = $checkType)");
            })
            ->when($cityCode, function ($query) use ($cityCode, $level) {
                switch ($level) {
                    case 1:
                        $codeText = 'provinceCode';
                        break;
                    case 3:
                        $codeText = 'areaCode';
                        break;
                    default:
                        $codeText = 'cityCode';
                        break;
                }
                $child = OpenShopAddressModel::query()
                    ->where($codeText, $cityCode)
                    ->select('orderNo');
                $query->whereRaw("orderNo in (" . BaseModel::toSqlWithParam($child) . ')');
            })
            ->get()
            ->each(function ($item) use (&$completed, &$notReview, &$notModify, &$notSubmit, &$closed, &$collected) {
                switch ($item->status) {
                    case CruiseOrderModel::STATUS_NOT_SUBMIT:
                        ++$notSubmit;
                        break;
                    case CruiseOrderModel::STATUS_NOT_REVIEW:
                    case CruiseOrderModel::STATUS_WAIT_MODIFY_EXT:
                        ++$notReview;
                        break;
                    case CruiseOrderModel::STATUS_NOT_MODIFY:
                        ++$notModify;
                        break;
                    case CruiseOrderModel::STATUS_COMPLETE:
                        ++$completed;
                        break;
                    case CruiseOrderModel::STATUS_COLLECTED:
                        ++$collected;
                        break;
                    case CruiseOrderModel::STATUS_CLOSED:
                        ++$closed;
                        break;
                }
            });
        return [
            'submitted' => $notSubmit,    //待提交
            'reviewed'  => $notReview,    //待审核
            'modified'  => $notModify,    //待修改
            'completed' => $completed,    //已完成
            'collected' => $collected,    //待领取
            'closed'    => $closed,       //已作废
        ];
    }

    /**
     * 代办任务详情
     * @param $authInfo
     * @param $id
     * @return array
     * @throws GuzzleException
     */
    public static function getMissionInfo($authInfo, $id, string $platformName = '')
    {
        $cruiseOrderModel = CruiseOrderModel::query()
            ->with(['orderManagerRel', 'cruiseCheckTaskRel', 'checkTaskDetailRel.cruiseCheckErrorRel', 'cruiseCheckCompanyRel'])
            ->find($id);

        if (null == $cruiseOrderModel) {
            return [];
        }

        $mainProcess = OpenShopMainProcessModel::query()->where('shopId', $cruiseOrderModel->shopId)->orderByDesc('id')->first();
        if (!$mainProcess) {
            BaseService::throwErr('不存在的开店签约记录');
        }

        $shopAddress = OpenShopAddressModel::getData((string)optional($mainProcess)->orderNo);

        $userBaseInfoRel = $mainProcess->userBaseInfoRel;
        $identityRel = $mainProcess->userIdentityCardRel;

        //省总
        if (in_array($cruiseOrderModel->type, [CruiseTemplateModel::TYPE_3, CruiseTemplateModel::TYPE_8]) && null != $shopAddress) {
            $provinceManager = OrganizationManageService::getProvinceInfoByProvinceCode($shopAddress->provinceCode)['operationName'] ?? '-';
        } else {
            $provinceManager = '-';
        }

        //加盟商姓名
        if (in_array($cruiseOrderModel->type, [CruiseTemplateModel::TYPE_3, CruiseTemplateModel::TYPE_8])  && $identityRel->count()) {
            $name = $identityRel->name;
            $age  = $identityRel->birthday ? (new Carbon($identityRel->birthday))->diffInYears() : '-';
        } else {
            $name = '-';
            $age  = '-';
        }

        //加盟商电话
        if (in_array($cruiseOrderModel->type, [CruiseTemplateModel::TYPE_3, CruiseTemplateModel::TYPE_8])  && null != $userBaseInfoRel) {
            $mobile = $userBaseInfoRel->mobile;
        } else {
            $mobile = '';
        }

        //门店信息
        if (in_array($cruiseOrderModel->type, [CruiseTemplateModel::TYPE_3, CruiseTemplateModel::TYPE_8]) ) {
            $shopInfo = (new RmsShopApi())->getShopByIds([$cruiseOrderModel->shopId], ['id', 'shopCode', 'name'])['data']['shopList'] ?? [];
            $shopList = array_column($shopInfo, null, 'id');
        } else {
            $shopList = [];
        }

        //区域信息
        if (in_array($cruiseOrderModel->type, [CruiseTemplateModel::TYPE_3, CruiseTemplateModel::TYPE_8])  && null != $shopAddress) {
            $area    = $shopAddress->addressPrefix;
            $address = (string)ShopModel::query()->where('id', $cruiseOrderModel->shopId)->value('address');
        } else {
            $area    = '';
            $address = '';
        }

        //督导
        $supervise            = '';  //营运督导
        $superviseMobile      = '';  //营运督导手机号
        $superviseId          = '';  // 督导用户id

        $checkSupervise       = '';  //稽核督导
        $checkSuperviseMobile = '';  //稽核督导手机号

        if ($cruiseOrderModel->orderManagerRel->count()) {
            foreach ($cruiseOrderModel->orderManagerRel as $value) {
                if ($value->type == OpenShopOrderManagerModel::MANAGER_TYPE_5) {
                    $supervise       = $value->managerName;
                    $superviseMobile = (new RmsUserApi())->getUserInfoByIds([$value->managerUid], ['mobile'])['data'][0]['mobile'] ?? '';
                    $superviseId     = $value->managerUid;
                    break;
                }
            }
        }

        if (in_array($cruiseOrderModel->type, [CruiseTemplateModel::TYPE_3, CruiseTemplateModel::TYPE_8]) ) {
            //先展示稽核督导  获得该门店的稽核督导
            $cruiseCheckManager = OrganizationManageUserService::getCruiseCheckManager($cruiseOrderModel->shopId);
            $checkSupervise     = $cruiseCheckManager['name'] ?? '';
            $checkSuperviseMobile    = $cruiseCheckManager['mobile'] ?? '';
        }

        $processModel = CruiseOrderProcessModel::query()
            ->with(['examineLogRel'])
            ->where('cruiseOrderId', $id)
            ->orderBy('createdAt')
            ->get();

        //获取处理人
        $userInfo    = RmsUserService::getRmsUserInfoByUserIds(array_merge($processModel->pluck('createdByUid')->toArray(), [$cruiseOrderModel->cretedByUid, $cruiseOrderModel->handlerId, (int)optional($cruiseOrderModel->checkTaskDetailRel)->dealUid]))['data'] ?? [];
        $userList    = array_column($userInfo, 'username', 'id');
        $step        = CruiseOrderProcessModel::PROCESS_CREATED;
        $stepStatus  = CruiseOrderProcessModel::STATUS_OK;
        $processList = $processModel->map(function ($item) use ($userList, &$step, &$stepStatus) {
            $desc = '';
            if (null != $item->examineLogRel) {
                $desc = $item->examineLogRel->content;
            }

            if ($item->step != CruiseOrderProcessModel::PROCESS_TRANSFER) {
                $step = $item->step;
            }

            $stepStatus = $item->status;
            return [
                'date'       => $item->createdAt->format('m-d H:i'),
                'time'       => $item->createdAt->format('Y-m-d H:i:d'),
                'handler'    => $userList[$item->createdByUid] ?? '系统',
                'status'     => in_array($item->step, [CruiseOrderProcessModel::PROCESS_REVIEWED, CruiseOrderProcessModel::PROCESS_EXT_REVIEWED]) ? $item->status : CruiseOrderProcessModel::STATUS_OK,
                'statusText' => in_array($item->step, [CruiseOrderProcessModel::PROCESS_REVIEWED, CruiseOrderProcessModel::PROCESS_EXT_REVIEWED]) ? (CruiseOrderProcessModel::STATUS_MAPPING[$item->status] ?? '-') : (CruiseOrderProcessModel::PROCESS_MAPPING[$item->step] ?? '-'),
                'desc'       => $desc,
            ];
        })->toArray();

        $nextStep = 0;
        if (!in_array($step, [CruiseOrderProcessModel::PROCESS_COMPLETED, CruiseOrderProcessModel::PROCESS_CANCEL])) {
            $nextProcess   = self::pushProcess($step, $stepStatus, $cruiseOrderModel);
            $processList[] = $nextProcess;
            $nextStep      = $nextProcess['nextStep'];
        }
        $isShow    = false;
        $submitter = '-';
        $cancel    = false;

        // 稽核任务这里可以增加一个除了提交人关闭外，当前门店督导也能关闭的操作
        if (($authInfo['userId'] == (int)optional($cruiseOrderModel->checkTaskDetailRel)->dealUid ||
                ($superviseId && $authInfo['userId'] == $superviseId)) &&
            in_array($cruiseOrderModel->status, [CruiseOrderModel::STATUS_NOT_SUBMIT ])) { // 取消待修改作废按钮显示
            $cancel = true;
        }

        if ($cruiseOrderModel->type == CruiseOrderModel::TYPE_NEW_SHOP_HELP) {
            $handle = $cruiseOrderModel->getCurrentHandlerInfo($cruiseOrderModel->status);
            if ($authInfo['userId'] == $handle['id'] || in_array($cruiseOrderModel->status, [CruiseOrderModel::STATUS_NOT_REVIEW, CruiseOrderModel::STATUS_COMPLETE])) {
                $isShow = true;
            }
            $submitter = $userList[$cruiseOrderModel->createdByUid] ?? '-';
        }
        if ($cruiseOrderModel->type == CruiseOrderModel::TYPE_CHECK) {
            (new CheckInputService($cruiseOrderModel->id))->getCurrentHandlerInfo($cruiseOrderModel->status);
            if ((int)optional($cruiseOrderModel->checkTaskDetailRel)->dealUid == $authInfo['userId'] || in_array($cruiseOrderModel->status, [CruiseOrderModel::STATUS_NOT_REVIEW, CruiseOrderModel::STATUS_COMPLETE, CruiseOrderModel::STATUS_WAIT_MODIFY_EXT])) {
                $isShow = true;
            }

        }
        if (in_array($cruiseOrderModel->type, [CruiseTemplateModel::TYPE_5, CruiseTemplateModel::TYPE_8]) ) {
            $handle = (new CheckInputService($cruiseOrderModel->id))->getCurrentHandlerInfo($cruiseOrderModel->status);
            if (in_array($authInfo['userId'], $handle['userIds']) || in_array($cruiseOrderModel->status, [CruiseOrderModel::STATUS_NOT_REVIEW, CruiseOrderModel::STATUS_COMPLETE])) {
                $isShow = true;
            }
            if ($nextStep) {
                $handle = (new CheckInputService($cruiseOrderModel->id))->getCurrentHandlerInfo($nextStep);
                if (in_array($authInfo['userId'], $handle['userIds']) || in_array($cruiseOrderModel->status, [CruiseOrderModel::STATUS_NOT_REVIEW, CruiseOrderModel::STATUS_COMPLETE])) {
                    $isShow = true;
                }
            }
        }

        switch ($cruiseOrderModel->status) {
            case CruiseOrderModel::STATUS_NOT_SUBMIT:
            case CruiseOrderModel::STATUS_NOT_MODIFY:
                $text = '填写表格';
                break;
            case CruiseOrderModel::STATUS_NOT_REVIEW:
            case CruiseOrderModel::STATUS_COMPLETE:
            case CruiseOrderModel::STATUS_WAIT_MODIFY_EXT:
                $text = '查看表格';
                break;
            default:
                $text = '查看表格';
        }

        $sysTemplate = (int)optional($cruiseOrderModel->checkTaskDetailRel)->sysTemplate;
        $cutOffTime  = (int)optional($cruiseOrderModel->cruiseCheckTaskRel)->endTime;

        // 工厂信息
        if ($cruiseOrderModel->cruiseCheckCompanyId) {
            $cruiseCheckCompany = CruiseCheckCompanyModel::getDataById($cruiseOrderModel->cruiseCheckCompanyId);
        } else {
            $cruiseCheckCompany = [];
        }

        // 专项任务，需要校验开始时间
        if (in_array($sysTemplate, [CruiseTemplateModel::SYS_TEMPLATE_SPECIAL, CruiseTemplateModel::SYS_TEMPLATE_FACTORY_SPECIAL])) {
            $startTime = $cruiseOrderModel->cruiseCheckTaskRel->startTime;
        } else {
            $startTime = 0;
        }

        // 工厂自检 - 创建、修改该、截止时间都是当天
        if ($sysTemplate == CruiseTemplateModel::SYS_TEMPLATE_FACTORY_SELF) {
            $createTime = $cutOffTime = $updateTime = $cruiseOrderModel->createdAt->toDateString();
        } else {
            $createTime = $cruiseOrderModel->createdAt->toDateString();
            $cutOffTime = $cutOffTime ? formatDateYmd($cutOffTime) : '-';
            $updateTime = $cruiseOrderModel->updatedAt->toDateString();
        }

        $submitterIds = [];
        if (in_array($cruiseOrderModel->type, [CruiseTemplateModel::TYPE_3, CruiseTemplateModel::TYPE_5, CruiseTemplateModel::TYPE_8])) {
            $sub = CheckInputService::getSingleton($cruiseOrderModel->id, 0)->getCurrentHandlerInfo($cruiseOrderModel->status, false);
            $submitter = $sub['userNames'] ?? '';
            $submitterIds = $sub['userIds'] ?? [];
        }

        // 自检 & 完成了，取最后的审核处理人
        if ($cruiseOrderModel->type == CruiseTemplateModel::TYPE_8
            && in_array($cruiseOrderModel->status, [CruiseOrderModel::STATUS_AUDIT_OK, CruiseOrderModel::STATUS_AUDIT_ERROR])) {

            // audit
            $audit = CruiseOrderProcessModel::query()
                                            ->where("cruiseOrderId", $id)
                                            ->where("step", CruiseOrderProcessModel::PROCESS_SELF_REVIEWED)
                                            ->orderByDesc("id")
                                            ->first();
            if ($audit) {
                $submitterIds = [$audit->createdByUid];
                $submitter = KmsUser::getUserInfo([$audit->createdByUid])[$audit->createdByUid] ?? '-';
            }
        }

        // 转交权限
        $transferButton = false;
        if ($cruiseOrderModel->type == CruiseTemplateModel::TYPE_3) {
            if (in_array($cruiseOrderModel->status, [CruiseOrderModel::STATUS_NOT_SUBMIT, CruiseOrderModel::STATUS_NOT_MODIFY])) {
                if (in_array($authInfo['userId'], $submitterIds)) {
                    $transferButton = true;
                }
            }
        }

        return [
            'info'              => [
                'id'      => $cruiseOrderModel->id,
                'orderNo' => $cruiseOrderModel->orderNo
            ],
            'baseInfo'          => [
                'supervise'      => $supervise ?: '-',
                'submitter'      => $submitter,
                'provinceManger' => $provinceManager,
                'checkManger'    => $userList[(int)optional($cruiseOrderModel->checkTaskDetailRel)->dealUid] ?? '-',
                'taskName'       => $cruiseOrderModel->getTaskName(), // 任务名称
                'sysTemplate'    => $sysTemplate,
                'taskType'       => CruiseTemplateModel::SYS_TEMPLATE_TEXT[$sysTemplate] ?? [],
                'status'         => $cruiseOrderModel->status,
                'invalidTypeText'=> CruiseCheckErrorModel::INVALID_TYPE_TEXT[(int)optional(optional($cruiseOrderModel->checkTaskDetailRel)->cruiseCheckErrorRel)->invalidType] ?? '',
                'invalidId'      => (int)optional(optional($cruiseOrderModel->checkTaskDetailRel)->cruiseCheckErrorRel)->id,
                'statusText'     => CruiseOrderModel::CRUISE_STATUS_MAPPING[$cruiseOrderModel->status] ?? '未知任务状态',
                'createTime'     => $createTime,
                'cutOffTime'     => $cutOffTime,
                'startTime'       => $startTime ? formatDateYmd($startTime) : '',
                'updateTime'     => $updateTime,
                'version'        => CruiseCheckAgainstService::shopVersion($cruiseOrderModel->shopId)['version'] ?? 'v4.0',

            ],
            'userInfo'          => [
                'name'   => $name,
                'age'    => $age,
                'mobile' => $mobile
            ],
            'shopInfo' => [
                'info'                 => 'KF' . sprintf("%04d", ($shopList[$cruiseOrderModel->shopId]['shopCode'] ?? '0000')) . ' ' . ($shopList[$cruiseOrderModel->shopId]['name'] ?? '-'),
                'area'                 => $area,
                'code'                 => $shopList[$cruiseOrderModel->shopId]['shopCode'] ?? '-',
                'name'                 => $shopList[$cruiseOrderModel->shopId]['name'] ?? '-',
                'shopId'               => $cruiseOrderModel->shopId,
                'address'              => $address,
                'supervise'            => $supervise ?: '-',
                'superviseMobile'      => $superviseMobile,
                'provinceManger'       => $provinceManager,
                'checkSupervise'       => $checkSupervise,
                'checkSuperviseMobile' => $checkSuperviseMobile,
            ],
            'company' => [
                'companyName'    => $cruiseCheckCompany['fsCompany']['name'] ?? '',
                'companyContact' => $cruiseCheckCompany['companyManager']['name'] ?? '',
                'companyPhone'   => $cruiseCheckCompany['companyManager']['phone'] ?? '',
                'kfManager'      => $cruiseCheckCompany['kfManager']['name'] ?? '',
                'companyId'      => $cruiseOrderModel->cruiseCheckCompanyId,
            ],
            'button'            => [
                'text'   => $text,
                'isShow' => $isShow
            ],
            'process'           => $processList,
            'cancelButton'      => $cancel,            //订单作废
            'receiveTaskButton' => self::receiveTask($cruiseOrderModel, $authInfo['userId']),       //领取任务按钮
            'transferButton'    => $transferButton,    // 任务转交按钮
            'inputs'            => in_array($cruiseOrderModel->type, [CruiseTemplateModel::TYPE_3, CruiseTemplateModel::TYPE_5, CruiseTemplateModel::TYPE_8]) ? (CheckInputService::getSingleton($cruiseOrderModel->id, 0)->getInputObjectFill()['lists'] ?? []) : [],   //根据类型决定是否展示
            'approvalOpinionConfig'=> configModel::getCruiseApprovalOpinionConfig(),//获取稽核整改建议配置
        ];
    }

    /**
     * 领取任务按钮
     * @param CruiseOrderModel $cruiseOrderModel
     * @param int $userId
     * @return bool
     */
    public static function receiveTask(CruiseOrderModel $cruiseOrderModel, int $userId): bool
    {
        $cruiseCheckDetailModel = $cruiseOrderModel->checkTaskDetailRel;

        if (!$cruiseCheckDetailModel) {
            return false;
        }

        // 门店常规巡检
        // 工厂常规自检
        if (in_array($cruiseCheckDetailModel->sysTemplate,
            [CruiseTemplateModel::SYS_TEMPLATE_COMMON, CruiseTemplateModel::SYS_TEMPLATE_FACTORY_SELF])) {
            return false;
        }

        // 门店专项
        if ($cruiseCheckDetailModel->sysTemplate == CruiseTemplateModel::SYS_TEMPLATE_SPECIAL) {

            if ($cruiseCheckDetailModel->dealUid != 0) {
                return false;
            }

            if ($cruiseCheckDetailModel->checkType != CruiseCheckDetailModel::CHECK_TYPE_THIRD_PARTY) {
                return false;
            }

            if ($cruiseOrderModel->status != CruiseOrderModel::STATUS_COLLECTED) {
                return false;
            }


            // 用户属于 专项指定的供应商就能领取
            $fsCompanyId = (int)FsCompanyModel::query()
                                              ->where('departmentId', $cruiseCheckDetailModel->companyId)
                                              ->value('id');
            if (!$fsCompanyId) {
                return false;
            }

            if (FsCompanyUserMappingModel::query()->where('fsCompanyId', $fsCompanyId)->where('rmsUserId', $userId)->exists()) {
                return true;
            }
        }

        // 工厂专项
        if ($cruiseCheckDetailModel->sysTemplate == CruiseTemplateModel::SYS_TEMPLATE_FACTORY_SPECIAL) {

            if ($cruiseCheckDetailModel->dealUid != 0) {
                return false;
            }

            $companyId = (string)optional($cruiseOrderModel->checkTaskDetailRel)->companyId;

            $fsCompanyId = (int)FsCompanyModel::query()
                                              ->where('departmentId', $companyId)
                                              ->value('id');

            if (FsCompanyUserMappingModel::query()->where('fsCompanyId', $fsCompanyId)->where('rmsUserId', $userId)->exists()) {
                return true;
            }
        }

        // 其他情况先不处理
        return false;
    }

    /**
     * 追加新的未完成任务
     * @return array
     */
    public static function pushProcess($step, $stepStatus, $cruiseOrderModel)
    {
        $nextStep   = 0;
        $handleName = '-'; //处理人
        if ($cruiseOrderModel->type == CruiseOrderModel::TYPE_NEW_SHOP_HELP) {
            switch ($step) {
                case CruiseOrderProcessModel::PROCESS_CREATED:
                    $nextStep = CruiseOrderProcessModel::PROCESS_SUBMITTED;
                    break;
                case CruiseOrderProcessModel::PROCESS_SUBMITTED:
                case CruiseOrderProcessModel::PROCESS_MODIFIED:
                    $nextStep = CruiseOrderProcessModel::PROCESS_REVIEWED;
                    break;
                case CruiseOrderProcessModel::PROCESS_REVIEWED:
                    if ($stepStatus == CruiseOrderProcessModel::STATUS_OFF) {
                        $nextStep = CruiseOrderProcessModel::PROCESS_MODIFIED;
                    } else {
                        $nextStep = CruiseOrderProcessModel::PROCESS_COMPLETED;
                    }
                    break;
                default:
                    $nextStep = CruiseOrderProcessModel::PROCESS_COMPLETED;
            }
            $handleName = $cruiseOrderModel->getCurrentHandlerInfo($nextStep)['name'] ?? '-';
        } elseif (in_array($cruiseOrderModel->type, [CruiseOrderModel::TYPE_CHECK, CruiseOrderModel::TYPE_COMPANY_CHECK])) {
            switch ($step) {
                case CruiseOrderProcessModel::PROCESS_CREATED:
                    if (in_array((int)optional($cruiseOrderModel->checkTaskDetailRel)->sysTemplate, [CruiseTemplateModel::SYS_TEMPLATE_SPECIAL, CruiseTemplateModel::SYS_TEMPLATE_FACTORY_SPECIAL]) && (int)optional($cruiseOrderModel->checkTaskDetailRel)->checkType == CruiseCheckDetailModel::CHECK_TYPE_THIRD_PARTY) {
                        $nextStep = CruiseOrderProcessModel::PROCESS_RECEIVE;
                    } else {
                        $nextStep = CruiseOrderProcessModel::PROCESS_SUBMITTED;
                    }
                    break;
                case CruiseOrderProcessModel::PROCESS_RECEIVE:
                    $nextStep = CruiseOrderProcessModel::PROCESS_SUBMITTED;
                    break;
                case CruiseOrderProcessModel::PROCESS_SUBMITTED:
                case CruiseOrderProcessModel::PROCESS_MODIFIED:
                    if (in_array((int)optional($cruiseOrderModel->checkTaskDetailRel)->sysTemplate, [CruiseTemplateModel::SYS_TEMPLATE_SPECIAL, CruiseTemplateModel::SYS_TEMPLATE_FACTORY_SPECIAL]) && (int)optional($cruiseOrderModel->checkTaskDetailRel)->checkType == CruiseCheckDetailModel::CHECK_TYPE_THIRD_PARTY) {
                        $nextStep = CruiseOrderProcessModel::PROCESS_EXT_REVIEWED;
                    } else {
                        $nextStep = CruiseOrderProcessModel::PROCESS_REVIEWED;
                    }
                    break;
                case CruiseOrderProcessModel::PROCESS_REVIEWED:
                    if (in_array((int)optional($cruiseOrderModel->checkTaskDetailRel)->sysTemplate, [CruiseTemplateModel::SYS_TEMPLATE_SPECIAL, CruiseTemplateModel::SYS_TEMPLATE_FACTORY_SPECIAL]) && (int)optional($cruiseOrderModel->checkTaskDetailRel)->checkType == CruiseCheckDetailModel::CHECK_TYPE_THIRD_PARTY) {
                        if ($stepStatus == CruiseOrderProcessModel::STATUS_OFF) {
                            $nextStep = CruiseOrderProcessModel::PROCESS_MODIFIED;
                        } else {
                            $nextStep = CruiseOrderProcessModel::PROCESS_REVIEWED;
                        }
                    } else {
                        $nextStep = CruiseOrderProcessModel::PROCESS_MODIFIED;
                    }
                    break;
                case CruiseOrderProcessModel::PROCESS_EXT_REVIEWED:
                    if ($cruiseOrderModel->status == CruiseOrderModel::STATUS_NOT_MODIFY) {
                        $nextStep = CruiseOrderProcessModel::PROCESS_MODIFIED;
                    } else {
                        $nextStep = CruiseOrderProcessModel::PROCESS_REVIEWED;
                    }
                    break;
                default:
                    $nextStep = CruiseOrderProcessModel::PROCESS_COMPLETED;
            }

            if (in_array((int)optional($cruiseOrderModel->checkTaskDetailRel)->sysTemplate, [CruiseTemplateModel::SYS_TEMPLATE_SPECIAL, CruiseTemplateModel::SYS_TEMPLATE_FACTORY_SPECIAL]) && (int)optional($cruiseOrderModel->checkTaskDetailRel)->checkType == CruiseCheckDetailModel::CHECK_TYPE_THIRD_PARTY) {
                $handleName = (new CheckInputService($cruiseOrderModel->id))->getCurrentHandlerInfo($nextStep)['userNames'] ?? '-';
            } else {
                if ($nextStep == CruiseOrderModel::STATUS_NOT_REVIEW && $cruiseOrderModel->type == CruiseOrderModel::TYPE_CHECK) {
                    $kuafuManager = ConfigModel::getCruiseCheckAudit($cruiseOrderModel->checkTaskDetailRel->companyId, $cruiseOrderModel->type, FsCompanyRoleMappingModel::ROLE_ID_KF_REVIEWER);
                    $handleName   = collect(RmsUserRemote::getRmsUserByIds($kuafuManager))->implode('username', ',');
                } else {
                    $handleName = (new CheckInputService($cruiseOrderModel->id))->getCurrentHandlerInfo($nextStep)['userNames'] ?? '-';
                }
            }
        }
        return [
            'date'       => '-',
            'handler'    => $handleName,
            'status'     => CruiseOrderProcessModel::STATUS_GREY,
            'statusText' => CruiseOrderProcessModel::PROCESS_PUSH_MAPPING[$nextStep] ?? '-',
            'nextStep'   => $nextStep,
            'desc'       => '',
        ];
    }
}
